import re
import json
import time
import os
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from configs.other_config import REGEX_FILE_PATH, REGEX_FOLDER_PATH


# 读取json文件
def load_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        datas = json.load(file)
    return datas


# 预编译正则规则
def precompiled_regex_relus():
    # 存储编译后的规则
    rules = {}

    # 遍历意图和规则
    for intent, intent_rules in regex_rules.items():
        compiled_intent_rules = [re.compile(rule, re.IGNORECASE) for rule in intent_rules]
        rules[intent] = compiled_intent_rules

    return rules


# 读取正则json文件
regex_rules = load_json_file(REGEX_FILE_PATH)
# 预编译正则规则
try:
    compiled_rules = precompiled_regex_relus()
    # 正则json文件是否正常
    regex_json = True
except:
    regex_json = False


class FileEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        global regex_rules, compiled_rules, regex_json
        if event.src_path == REGEX_FILE_PATH:
            try:
                regex_json = True
                # 读取正则json文件
                regex_rules = load_json_file(REGEX_FILE_PATH)
                # 预编译正则规则
                compiled_rules = precompiled_regex_relus()
                # 文件修改时间
                modification_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                log_message = f"{os.path.basename(REGEX_FILE_PATH)} modified at {modification_time}"
                print(log_message)
            except:
                regex_json = False
                print(f"There is a problem with the {os.path.basename(REGEX_FILE_PATH)} file.")


observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler, REGEX_FOLDER_PATH, True)
observer.start()


# 法律咨询2正则规则
law_regex_rules = [
    re.compile(
        r'.*(你(能|可以)|告诉我|要|我(需要|想要|请求)|发起|开始|进行|帮?我(想|要)(找|咨询一下))?(法律|律师)(咨询|援助|帮助|服务|事务所).*'),
    re.compile(r'.*(告诉我|播报|我需?要|(讲|说|介绍)一(下|个))(律所|律师)(电话|律师事务所).*'),
    re.compile(r'.*(我|你)可以(咨询|回答|问你)法律(相关)?问题吗.*'),
    re.compile(r'.*我要打官司.*')
]


# 法律咨询2
async def law_relu(prompt):
    law_relu.matching_type = "regex"
    try:
        for i in compiled_rules["law"]:
            if re.match(i, prompt):
                return '2'
    except:
        for i in law_regex_rules:
            if re.match(i, prompt):
                return '2'
    return None


# 卡车维修3正则规则
repair_regex_rules = [
    re.compile(r'.*(我的?卡?车(出问题了|坏了)(怎么办？?)?|(你|我)可以(回答|问你)卡车维修的问题吗？?).*'),
    re.compile(r'.*(我((想|需)?要))?维修(卡|汽)车(联系)?(电话)?.*'),
    re.compile(r'.*(卡车)?(维修|售后)(服务|联系)(电话|服务).*'),
    re.compile(r'.*卡车维修.*'),
    re.compile(r'.*保养(卡车|重卡).*'),
    re.compile(r'.*(卡车|重卡)保养.*')
]


# 卡车维修3
async def automobile_maintenance_relu(prompt):
    automobile_maintenance_relu.matching_type = "regex"
    try:
        for i in compiled_rules["repair"]:
            if re.match(i, prompt):
                return '3'
    except:
        for i in repair_regex_rules:
            if re.match(i, prompt):
                return '3'
    return None


# 车祸4正则规则
accident_regex_rules = [
    re.compile(r'.*(出现)?车祸了?(怎么办|找谁)?.*'),
    re.compile(r'.*(撞车|追尾|撞人|(交通|卡车)事故).*'),
    re.compile(r'.*(报警|火警|急救)电话.*')
]


# 车祸4
async def car_accident_relu(prompt):
    car_accident_relu.matching_type = "regex"
    try:
        for i in compiled_rules["accident"]:
            if re.match(i, prompt):
                return '4'
    except:
        for i in accident_regex_rules:
            if re.match(i, prompt):
                return '4'
    return None


# 卡车购买推荐5正则规则
buy_truck_regex_relus = [
    re.compile(r'.*我?(想|要)?(购?买|买一辆)新?(卡车|重卡).*'),
    re.compile(r'.*(我(要|想))?买(新|牵引|载货|自卸|(解放)?卡)车.*'),
    re.compile(r'.*怎么买卡?车.*'),
    re.compile(r'.*(小卡你能给我一些)?卡车(购买)?(电话|推荐|意见|建议)吗?.*'),
    re.compile(r'.*(解放|一汽)(卡车|重卡)购买.*'),
    re.compile(r'.*售车(电话|热线)?.*')
]


# 卡车购买推荐5
async def buy_truck_relu(prompt):
    buy_truck_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["buy_truck"]:
            if re.match(i, prompt):
                return '5'
    except:
        for i in buy_truck_regex_relus:
            if re.match(i, prompt):
                return '5'
    return None


# 天气9正则规则
weather_regex_rules = [
    re.compile(
        r'((.*(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)(现在|(.天))?.?天气(咋|怎么)?样?(预报)?(吗|啊)?[，。！？]?(小卡)?)|当前天气).*'),
    re.compile(r'.*(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)?(现在|(.天))?.?气温(吗|啊)?[，。！？]?(小卡)?.*'),
    re.compile(r'^(小卡)*[，。！？]?(播报|告诉我|讲一下|说一下)?(现在|(.天))?.?温度(吗|啊)?[，。！？]?(小卡)?$'),
    re.compile(r'.*(今天|现在)?((天气|温度)((怎么|咋)样|好吗)|适合外出吗|(几|多少)度).*'),
    re.compile(r'^(小卡)*[，。！？]?(天气|温度)[？，。！]?$')
]


# 天气9
async def weather_relu(prompt):
    weather_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["weather"]:
            if re.match(i, prompt):
                return '9'
    except:
        for i in weather_regex_rules:
            if re.match(i, prompt):
                return '9'
    return None


# 打招呼10正则规则
greeting_regex_rules = [
    re.compile(r'.*(小卡)*[，。！？]?(您好|早上好|hello|hi|hey|晚上好|上午好|中午好|下午好)[，。！？]?啊?(小卡)?',
               re.IGNORECASE),
    re.compile(r'^(小卡)*[，。！？]?(你好)[，。！？]?啊?(小卡)?[？，。！]?$', re.IGNORECASE),
]


# 打招呼10
async def greeting_relu(prompt):
    greeting_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["greeting"]:
            if re.match(i, prompt):
                return '10'
    except:
        for i in greeting_regex_rules:
            if re.match(i, prompt):
                return '10'
    return None


# 时间11正则规则
time_regex_rules = [
    re.compile(
        r'^(小卡)*[，。！？]?(((播报|告诉我|讲一下|说一下)?(当前|现在)?.?(什么)?时间(吗|啊|了)?[，。！？]?(小卡)?$)|当前时间|现在是?什么(时候|时间)(了|呢)啊?|现在是?什么(时候|时间)(了|呢)?啊?)[，。！？]?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*几点钟?了?(吗|啊)?[，。！？]?(小卡)?$'),
    re.compile(r'.*(小卡)*[，。！？]?(告诉我|播报|讲一下|说一下)?.*时辰了?(吗|啊)?[，。！？]?(小卡)?$')
]


# 时间11
async def time_relu(prompt):
    time_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["time"]:
            if re.match(i, prompt):
                return '11'
    except:
        for i in time_regex_rules:
            if re.match(i, prompt):
                return '11'
    return None


# 日期、星期几正则规则
date_regex_relus = [
    re.compile(r'^(小卡)*.?[，。！？]*(今天|现在|今儿?个)?(几月)?(几号了?|(周|星期|礼拜)几)(啊|呢|呀)?[？，。！]?$')
]


async def date_relu(prompt):
    date_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["date"]:
            if re.match(i, prompt):
                return 'date'
    except:
        for i in date_regex_relus:
            if re.match(i, prompt):
                return 'date'
    return None


# 人工服务12正则规则
service_regex_relus = [
    re.compile(r'.*(告诉我|播报|(讲|说)(一下)?|联系)?(人工|客服)(电话|服务|客服)(是多少)?.*')
]


# 人工服务12
async def service_relu(prompt):
    service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["service"]:
            if re.match(i, prompt):
                return '12'
    except:
        for i in service_regex_relus:
            if re.match(i, prompt):
                return '12'
    return None





# 跳舞54正则规则
dance_regex_relus = [
    re.compile(r'.*(展示)?(舞蹈|(跳|来)一?(个|支|段)舞).*'),
    re.compile(r'.*你(能|会)跳舞吗[？，。！]?'),
    re.compile(r'^(小+卡)*[？，。！]?跳舞[？，。！]?')
]


# 跳舞54
async def dance_relu(prompt):
    dance_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["dance"]:
            if re.match(i, prompt):
                return '54'
    except:
        for i in dance_regex_relus:
            if re.match(i, prompt):
                return '54'
    return None




# 附近/位置问题正则规则
neighborhood_problem_regex_relus = [
    re.compile(r'.*(附近|身边|旁边|周围|边上)(哪里)?有.*'),
    re.compile(r'^(小卡)*[，。！？]?(当前)?位置[？，。！]?$'),
    re.compile(r'.*(小卡)*[，。！？]?我(现在|当前)(位置)?在哪[？，。！]?.*')
]


# 附近问题
async def neighborhood_problem_relu(prompt):
    neighborhood_problem_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["neighborhood_problem"]:
            if re.match(i, prompt):
                return '附近'
    except:
        for i in neighborhood_problem_regex_relus:
            if re.match(i, prompt):
                return '附近'
    return None



# 东风客服电话67
DONGFENG_service_regex_relus = [
    re.compile(r'.*东风((卡|商用)车)?(服务|客服|售后)(电话|热线).*')
]


# 东风客服67
async def dongfeng_service_relu(prompt):
    dongfeng_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["dongfeng_service"]:
            if re.match(i, prompt):
                return '67'
    except:
        for i in DONGFENG_service_regex_relus:
            if re.match(i, prompt):
                return '67'
    return None


# 陕汽客服电话68
SHANQI_service_regex_relus = [
    re.compile(r'.*陕汽((卡|商用)车)?(服务|客服|售后)(电话|热线).*')
]


# 陕汽客服68
async def shanqi_service_relu(prompt):
    shanqi_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["shanqi_service"]:
            if re.match(i, prompt):
                return '68'
    except:
        for i in SHANQI_service_regex_relus:
            if re.match(i, prompt):
                return '68'
    return None


# 中国重汽客服电话69
SINOTRUK_service_regex_relus = [
    re.compile(r'.*(中国)?重汽(卡车)?(客服|服务|售后)(电话|热线).*')
]


# 中国重汽客服69
async def sinotruk_service_relu(prompt):
    sinotruk_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["sinotruk_service"]:
            if re.match(i, prompt):
                return '69'
    except:
        for i in SINOTRUK_service_regex_relus:
            if re.match(i, prompt):
                return '69'
    return None


# 福田客服电话70
FOTON_service_regex_relus = [
    re.compile(r'.*(福田|欧曼)(卡车|戴勒姆)?(服务|客服|售后)(电话|热线).*')
]


# 福田客服70
async def foton_service_relu(prompt):
    foton_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["foton_service"]:
            if re.match(i, prompt):
                return '70'
    except:
        for i in FOTON_service_regex_relus:
            if re.match(i, prompt):
                return '70'
    return None


# 解放客服电话71
FAW_service_regex_relus = [
    re.compile(r'.*(一汽)?解放(卡车)?(服务|客服|售后)(电话|热线).*')
]


# 福田客服71
async def faw_service_relu(prompt):
    faw_service_relu.matching_type = 'regex'
    try:
        for i in compiled_rules["faw_service"]:
            if re.match(i, prompt):
                return '71'
    except:
        for i in FAW_service_regex_relus:
            if re.match(i, prompt):
                return '71'
    return None


# 意图识别
async def intent_recognition(prompt):
    result = await buy_truck_relu(prompt)
    if result is not None:
        return result

    result = await law_relu(prompt)
    if result is not None:
        return result

    result = await dance_relu(prompt)
    if result is not None:
        return result

    result = await automobile_maintenance_relu(prompt)
    if result is not None:
        return result

    result = await car_accident_relu(prompt)
    if result is not None:
        return result

    result = await weather_relu(prompt)
    if result is not None:
        return result

    result = await date_relu(prompt)
    if result is not None:
        return result

    result = await time_relu(prompt)
    if result is not None:
        return result

    result = await faw_service_relu(prompt)
    if result is not None:
        return result

    result = await dongfeng_service_relu(prompt)
    if result is not None:
        return result

    result = await shanqi_service_relu(prompt)
    if result is not None:
        return result

    result = await sinotruk_service_relu(prompt)
    if result is not None:
        return result

    result = await foton_service_relu(prompt)
    if result is not None:
        return result

    result = await service_relu(prompt)
    if result is not None:
        return result

    result = await neighborhood_problem_relu(prompt)
    if result is not None:
        return result

    result = await greeting_relu(prompt)
    if result is not None:
        return result

    # 如果没有匹配到任何意图，则返回None
    return None
